<script setup>
import { ref, onMounted, computed } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
import { insertArticle } from '../api/article'

const router = useRouter()
const route = useRoute()

const isNewArticle = ref(true)
const activeTab = ref('basic')
const previewVisible = ref(false)

// 田字格相关配置
const gridSizes = ref([
  { cols: 6, rows: 2, label: '6*2' },
  { cols: 6, rows: 3, label: '6*3' },
  { cols: 8, rows: 2, label: '8*2' },
  { cols: 8, rows: 4, label: '8*4' },
  { cols: 9, rows: 7, label: '9*7' }
])
const selectedGridSize = ref({ cols: 8, rows: 4 }) // 默认选择8*4的田字格

const article = ref({
  id: '',
  title: '',
  category: '',
  type: '',
  interest: 1,
  content: ''
})

const rules = {
  title: [
    { required: true, message: '请输入文章标题', trigger: 'blur' },
    { min: 3, max: 50, message: '标题长度应在3到50个字符之间', trigger: 'blur' }
  ],
  content: [
    { required: true, message: '请输入文章内容', trigger: 'blur' }
  ]
}

const handleSubmit = async () => {
  if (!article.value.title || !article.value.content) {
    ElMessage.error('文章标题和内容不能为空')
    return
  }

  try {
    await insertArticle({
      title: article.value.title,
      type: article.value.type,
      category: article.value.category,
      funny: article.value.interest,
      content: article.value.content
    })
    ElMessage.success('文章保存成功')
    router.push('/')
  } catch (error) {
    console.error('保存文章失败：', error)
    ElMessage.error('保存文章失败')
  }
}

const goBack = () => {
  router.push('/')
}

const handlePreview = () => {
  previewVisible.value = true
}

const paragraphs = computed(() => {
  return article.value.content
    ? article.value.content.split('\n').filter(p => p.trim())
    : [];
});

// 将段落文字转换为田字格数组
const getGridCharacters = (text) => {
  return text.split('').filter(char => char.trim());
};

// 选择田字格大小
const selectGridSize = (size) => {
  selectedGridSize.value = size;
};

onMounted(() => {
  const id = route.query.id;
  if (id) {
    isNewArticle.value = false;
    article.value = {
      id,
      title: '示例文章',
      category: 'regular',
      type: 'story',
      interest: 4,
      content: '在一个遥远的山谷里，住着一位聪明勇敢的牧羊人，名叫阿布。阿布每天都会带着他的羊群到山谷里的草地上放牧。他总是小心翼翼地照看着羊群，确保它们安全无忧。\n有一天，山谷里来了一只凶猛的狼。这只狼非常狡猾，它每天都会悄悄地接近羊群，试图抓走几只羊。阿布里然后小心地观察着狼的动向，但狼总是能逃脱。'
    };
  }
});
</script>

<template>
  <div class="article-edit">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span>{{ isNewArticle ? '新建文章' : '编辑文章' }}</span>
          <el-button type="primary" link @click="goBack">返回列表</el-button>
        </div>
      </template>

      <el-form ref="articleForm" :model="article" :rules="rules" label-width="100px">
        <el-tabs v-model="activeTab">
          <el-tab-pane label="基本信息" name="basic">
            <el-form-item label="文章标题" prop="title">
              <el-input v-model="article.title" placeholder="请输入文章标题" />
            </el-form-item>

            <el-form-item label="文章分类">
              <el-input v-model="article.category" placeholder="请输入文章分类" />
            </el-form-item>

            <el-form-item label="文章类型">
              <el-input v-model="article.type" placeholder="请输入文章类型" />
            </el-form-item>

            <el-form-item label="有趣度">
              <el-rate v-model="article.interest" :max="4" :min="1" show-score />
            </el-form-item>
          </el-tab-pane>

          <el-tab-pane label="文章内容" name="content">
            <el-form-item prop="content">
              <div class="content-header">
                <el-button type="primary" @click="handlePreview" :disabled="!article.content">预览</el-button>
              </div>
              <el-input v-model="article.content" type="textarea" :rows="15" placeholder="请输入文章内容" />
            </el-form-item>
          </el-tab-pane>
        </el-tabs>

        <el-dialog v-model="previewVisible" title="文章预览" width="80%" class="preview-dialog">
          <div class="grid-size-selector">
            <div class="grid-size-title">选择田字格大小：</div>
            <div class="grid-size-options">
              <div 
                v-for="size in gridSizes" 
                :key="`${size.cols}*${size.rows}`"
                :class="['grid-size-option', { 'active': selectedGridSize.cols === size.cols && selectedGridSize.rows === size.rows }]"
                @click="selectGridSize(size)"
              >
                {{ size.label }}
              </div>
            </div>
          </div>
          
          <div class="preview-container">
            <div class="preview-left">
              <div v-if="paragraphs.length">
                <div v-for="(paragraph, index) in paragraphs" :key="index" class="preview-paragraph">
                  <div class="paragraph-number">第{{ index + 1 }}段</div>
                  <div class="paragraph-content">
                    <!-- 普通文本显示 -->
                    <div class="normal-text">{{ paragraph }}</div>
                    
                    <!-- 田字格显示 -->
                    <div class="grid-container" :style="{
                      gridTemplateColumns: `repeat(${selectedGridSize.cols}, 1fr)`,
                      width: `${selectedGridSize.cols * 40}px`
                    }">
                      <div 
                        v-for="(char, charIndex) in getGridCharacters(paragraph)" 
                        :key="charIndex" 
                        class="grid-cell"
                        :class="{ 'highlight': charIndex >= 40 }"
                      >
                        {{ char }}
                      </div>
                    </div>
                  </div>
                </div>
              </div>
              <div v-else>
                <p>暂无内容</p>
              </div>
            </div>
            <div class="preview-right">
              <div class="original-content">{{ article.content }}</div>
            </div>
          </div>
        </el-dialog>

        <el-form-item>
          <el-button type="primary" @click="handleSubmit">保存</el-button>
          <el-button @click="goBack">取消</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<style scoped>
.article-edit {
  height: 100%;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.el-tabs {
  margin-bottom: 20px;
}

.content-header {
  margin-bottom: 10px;
  text-align: right;
}

.preview-dialog :deep(.el-dialog__body) {
  padding: 20px;
}

.preview-container {
  display: flex;
  gap: 20px;
  height: 60vh;
}

.preview-left,
.preview-right {
  flex: 1;
  overflow-y: auto;
  padding: 10px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
}

.preview-paragraph {
  margin-bottom: 15px;
  padding: 10px;
  background-color: #f5f7fa;
  border-radius: 4px;
  display: flex;
  gap: 10px;
}

.paragraph-number {
  font-weight: bold;
  color: #409EFF;
  min-width: 60px;
}

.paragraph-content {
  white-space: pre-wrap;
  word-break: break-word;
  flex: 1;
}

.original-content {
  white-space: pre-wrap;
  word-break: break-word;
}

/* 田字格相关样式 */
.grid-size-selector {
  margin-bottom: 20px;
  display: flex;
  align-items: center;
  gap: 10px;
}

.grid-size-title {
  font-weight: bold;
}

.grid-size-options {
  display: flex;
  gap: 10px;
}

.grid-size-option {
  padding: 5px 15px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.3s;
}

.grid-size-option:hover {
  background-color: #f5f7fa;
}

.grid-size-option.active {
  background-color: #e815c7;
  color: white;
  border-color: #e815c7;
}

.normal-text {
  margin-bottom: 15px;
}

.grid-container {
  display: grid;
  gap: 1px;
  background-color: #dcdfe6;
  border: 1px solid #dcdfe6;
}

.grid-cell {
  height: 40px;
  background-color: white;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 18px;
}

.grid-cell.highlight {
  background-color: #ff4d4f;
  color: white;
}
</style>